/**
 * JAVACC DEMO 1.0
 * @copy right iussoft company All rights reserved.
 * @Package com.iussoft.portal.send
 */
package com.apache.portal.common.template;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

import com.apache.portal.common.util.FileOperate;
import com.apache.uct.common.ToolsUtil;

/**
 * description:  模板解析
 * @author qihan 创建时间：2017-7-24  
 */
public class TemplateConverter {
	protected Logger log = Logger.getLogger(getClass());

	private final String COMMON_ALL_TAG_TEMPLATE_START = "(<!-- temp=\\s+[\\s\\S]*? start -->)";
	private final String COMMON_HEAD_TAG_TEMPLATE = "(<!-- temp=\\s+[\\s\\S]*? end -->)";

	public Object execute(Map<String, String> param) throws Exception {
		String fileName = param.get("incFileName");
		String content = param.get("converContent");
		String tempId = param.get("tempId");
		String flagType = param.get("flagType");
		String fileRootPath = ToolsUtil.getInstance().getLocalByKey("config.properties","html_path");
		//后台使用
		if ("admin".equals(flagType)) {
			fileRootPath = ToolsUtil.getInstance().getLocalByKey("config.properties","jsp_path");
			content = content.replaceAll("<br>", "\n").replaceAll("&nbsp;", "\t");
			content = content.replaceAll("<!--", "").replaceAll("-->", "");
		}
		log.info("开始替换文件[" + fileRootPath + fileName + "]中内容");
		File file = new File(fileRootPath + fileName);
		if (!file.exists()) {
			log.info("此文件不存在！！！");
			return false;
		}
		InputStream in = new FileInputStream(file);
		String tempContent = IOUtils.toString(in, "UTF-8");
		int start = tempContent.indexOf("<!-- temp=\"" + tempId + "\" start -->");
		int end = tempContent.indexOf("<!-- temp=\"" + tempId + "\" end -->");
		StringBuffer sb = new StringBuffer("");
		sb.append(tempContent.substring(0, start));
		sb.append("<!-- temp=\"" + tempId + "\" start -->\n");
		sb.append(content);
		sb.append("\n\t\t\t\t" + tempContent.substring(end));
		return FileOperate.getInstance().newCreateFile(fileRootPath + fileName, sb.toString());
		//return sb.toString();
	}

	public Object exeRandomAccessFile(Map<String, String> param) {

		return null;
	}
}
